//
//  YTScaleAnimator.swift
//  YTImgeViewer
//
//  Created by aron on 2018/5/25.
//

import Foundation

/// 动画效果
class YTScaleAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    
    var transitionFromView: UIView?
    var transitionToView: UIView?
    var transitionAnimatedView: UIView?
    
    init(transitionFromView: UIView?, transitionToView: UIView?, transitionAnimatedView: UIView?) {
        self.transitionFromView = transitionFromView
        self.transitionToView = transitionToView
        self.transitionAnimatedView = transitionAnimatedView
        super.init()
    }
    
    public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.3
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let containerView = transitionContext.containerView
        guard let startView = transitionFromView, let transitionView = transitionAnimatedView, let endView = transitionToView else {
            transitionContext.completeTransition(false)
            return
        }
        
        guard let fromVC = transitionContext.viewController(forKey: .from),
            let toVC = transitionContext.viewController(forKey: .to) else {
                transitionContext.completeTransition(false)
                return
        }
        let isPresent = fromVC.presentedViewController == toVC
        if !isPresent {
            // Dismiss特殊处理
            startView.alpha = 0.01
        }
        
        //有渐变的黑色背景
        let bgView = UIView.init(frame: containerView.bounds)
        bgView.backgroundColor = UIColor.black
        bgView.alpha = isPresent ? 0 : 1
        containerView.addSubview(bgView)
        
        // 计算转场元素的开始和结束Frame
        let startFrame = startView.convert(startView.bounds, to: containerView)
        let endFrame = endView.convert(endView.bounds, to: containerView)

        transitionView.frame = startFrame
        containerView.addSubview(transitionView)
        
        // 执行转场动画
        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
            transitionView.frame = endFrame
            bgView.alpha = isPresent ? 1 : 0
        }) { _ in
            if let toView = transitionContext.view(forKey: .to) {
                containerView.addSubview(toView)
            }
            bgView.removeFromSuperview()
            transitionView.removeFromSuperview()
            transitionContext.completeTransition(true)
        }
    }
}

